package com.example.ykbboom.universitytransportation.Activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.bumptech.glide.Glide;
import com.example.ykbboom.universitytransportation.MyApplication;
import com.example.ykbboom.universitytransportation.POJO.RequestDetailItem;
import com.example.ykbboom.universitytransportation.R;
import com.example.ykbboom.universitytransportation.Util.LogUtil;
import com.example.ykbboom.universitytransportation.Util.NetUtil;
import com.example.ykbboom.universitytransportation.Util.SharedPrefUtil;
import com.example.ykbboom.universitytransportation.Util.ToastUtil;
import com.example.ykbboom.universitytransportation.View.DividerItemDecoration;
import com.example.ykbboom.universitytransportation.View.RequestDetailAdapter;

import java.util.ArrayList;
import java.util.List;

public class RequestDetailActivity extends BaseActivity {

    private static String TAG = RequestDetailActivity.class.getSimpleName();
    private Toolbar mToolbar;
    private List<RequestDetailItem>list = new ArrayList<>();
    private RecyclerView recyclerView;
    private ImageView thingImgView;
    private RequestDetailAdapter requestDetailAdapter;
    private Button detailBtn;//功能分为接单或者删除请求
    private ProgressDialog progressDialog;
    private AMapLocationClient aMapLocationClient;
    private AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            //定位成功,提交数据
            if (aMapLocation != null) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    LogUtil.i(TAG,"车主当前的位置数据："+aMapLocation.getCity()+","+aMapLocation.getLatitude()+","+aMapLocation.getLongitude());
                    NetUtil.driverCompleteOrder(String.valueOf(aMapLocation.getLongitude())+","+String.valueOf(aMapLocation.getLatitude())
                    ,SharedPrefUtil.getUserPhone(),getIntent().getIntExtra("requestId",0),progressDialog);
                } else {
                    LogUtil.e(TAG,"定位失败,"+aMapLocation.getErrorCode()+":"+aMapLocation.getErrorInfo());
                }
            }
        }
    };
    private AMapLocationClientOption aMapLocationClientOption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request_detail);
        initView();
    }

    @Override
    public void initView() {
        progressDialog = new ProgressDialog(this);
        mToolbar = (Toolbar) findViewById(R.id.toolbar_request_detail);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setHomeButtonEnabled(true); //设置返回键可用
            actionBar.setDisplayHomeAsUpEnabled(true);//显示HomeAsUp按钮
            actionBar.setDisplayShowTitleEnabled(false);//不自动显示标题
        }
        detailBtn = (Button) findViewById(R.id.request_detail_btn);
        detailBtn.setOnClickListener(this);
        if (getIntent().getStringExtra("activityName").equals("MainActivity")) {
            detailBtn.setText("接单");
        }else if(getIntent().getStringExtra("activityName").equals("MyRequestActivity")&&!getIntent().getStringExtra("completeMsg").equals("已完成")){
            detailBtn.setText("删除此单");
        }else if(getIntent().getStringExtra("activityName").equals("MyOrderActivity")){
            detailBtn.setText("已到达目的地");
        }else if (getIntent().getStringExtra("activityName").equals("MyRequestActivity")&&getIntent().getStringExtra("completeMsg").equals("已完成")){
            detailBtn.setText("确认订单完成");
        }
        recyclerView = (RecyclerView) findViewById(R.id.request_detail_recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        initList();
        requestDetailAdapter = new RequestDetailAdapter(list);
        recyclerView.setAdapter(requestDetailAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        thingImgView = (ImageView) findViewById(R.id.request_detail_imageView);
        Glide.with(this).load(getIntent().getStringExtra("picurl")).centerCrop().into(thingImgView);
    }
    /**
     * 初始化列表数据
     * */
    private void initList(){
        RequestDetailItem requestDetailItem = new RequestDetailItem(R.drawable.detail_account,getIntent().getStringExtra("userName"));
        RequestDetailItem requestDetailItem2 = new RequestDetailItem(R.drawable.detail_phone,getIntent().getStringExtra("userPhone"));
        RequestDetailItem requestDetailItem3 = new RequestDetailItem(R.drawable.detail_place,getIntent().getStringExtra("place"));
        RequestDetailItem requestDetailItem4 = new RequestDetailItem(R.drawable.detail_description,getIntent().getStringExtra("description"));
        RequestDetailItem requestDetailItem5 = new RequestDetailItem(R.drawable.detail_time,getIntent().getStringExtra("time")+"("+getIntent().getStringExtra("completeMsg")+")");
        list.add(requestDetailItem);//用户
        list.add(requestDetailItem2);//电话
        list.add(requestDetailItem5);//时间
        list.add(requestDetailItem3);//地点
        list.add(requestDetailItem4);//要求描述
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.request_detail_btn:
                if (detailBtn.getText().equals("删除此单")){
                    //删除请求
                    new AlertDialog.Builder(this)
                            .setTitle("请确认")
                            .setMessage("确定要删除吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    NetUtil.deleteUserRequest(getIntent().getIntExtra("requestId",0),getIntent().getIntExtra("position",0),RequestDetailActivity.this);
                                }
                            }).show();
                    break;
                }else if(detailBtn.getText().equals("接单")){
                    //接单
                    if (SharedPrefUtil.getDriverState()){
                        new AlertDialog.Builder(this)
                                .setTitle("请确认")
                                .setMessage("确定要接单吗？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        NetUtil.acceptRequest(SharedPrefUtil.getUserPhone(),getIntent().getStringExtra("gdIdStart"),RequestDetailActivity.this);
                                    }
                                }).show();
                        break;
                    }else {
                        ToastUtil.showToast(RequestDetailActivity.this,"请先成为车主再接单");
                        break;
                    }
                }else if(detailBtn.getText().equals("已到达目的地")) {
                    //车主完成此单
                    showDialog();
                    aMapLocationClient = new AMapLocationClient(getApplicationContext());
                    //设置定位回调监听
                    aMapLocationClient.setLocationListener(mLocationListener);
                    aMapLocationClientOption = getAMapLocationClientOption();
                    aMapLocationClient.setLocationOption(aMapLocationClientOption);
                    aMapLocationClient.startLocation();
                    break;
                }else if(detailBtn.getText().equals("确认订单完成")) {
                    //用户确认完毕
                    showDialog();
                    NetUtil.userConfirmOrder(getIntent().getIntExtra("requestId",0),progressDialog);
                    break;
                }
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationListener = null;
        if (aMapLocationClient != null) {
            aMapLocationClient.stopLocation();
            aMapLocationClient.onDestroy();
        }
        aMapLocationClient = null;
    }

    private AMapLocationClientOption getAMapLocationClientOption(){
        //设置发起定位的模式和相关参数
        AMapLocationClientOption mLocationClientOption = new AMapLocationClientOption();
        mLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mLocationClientOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mLocationClientOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mLocationClientOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mLocationClientOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mLocationClientOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mLocationClientOption.setOnceLocationLatest(true);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mLocationClientOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mLocationClientOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationClientOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mLocationClientOption;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
        }
        return true;
    }

    public void showDialog() {
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("loading...");
        progressDialog.show();
    }
}
